// AudioManager.cs
//

using System;
using System.Collections.Generic;

using Moonbeam.Core;

namespace Moonbeam.Media
{    
    public class AudioManager
    {
        List<Sound> sounds = null;
        int activeSoundsCount;
        int maxConcurentSounds;

        /// <summary>
        /// create a new audio manager
        /// </summary>
        /// <param name="_maxConcurentSounds">The maximum number of sounds palyable concurently, use lower values to improve performance
        /// and to reduce the audio tags added to your page</param>
        public AudioManager(int _maxConcurentSounds)
        {
            maxConcurentSounds = _maxConcurentSounds;

            sounds = new List<Sound>(maxConcurentSounds);
        }

        public void Update(GameTime gameTime)
        {
            activeSoundsCount = sounds.Count;

            for (int i = 0; i < sounds.Count-1; i++)
            {
                if (sounds[i].IsActive)
                {
                    sounds[i].Update(gameTime);
                    activeSoundsCount--;
                }
            }
        }

        public Sound AddSound(string _path, float _volume, bool _playNow)
        {
            if (activeSoundsCount >= maxConcurentSounds)
            {
                return null;
            }

            Sound newSound = null;

            newSound = new Sound(_path);
            newSound.SetVolume(_volume);

            if (sounds.Count < maxConcurentSounds)
            {
                sounds.Add(newSound);
            }
            else
            {
                //find an inactive sound
                for (int i = 0; i < sounds.Count-1; i++)
                {
                    if (!sounds[i].IsActive)
                    {
                        sounds[i] = newSound;
                        break;
                    }
                }
            }
            
            if (_playNow)
            {
                newSound.Play();
            }

            return newSound;
        }

        public void StopAll()
        {
            for (int i = 0; i < sounds.Count-1; i++)
            {
                sounds[i].Stop();
            }
        }
    }
}
